<?php

namespace app\service;

use app\exception\ErrnoPlus;
use app\model\CountryCodeModel;
use share\exception\ApiException;
use share\service\BaseModelService;
use share\utils\Helper;

class CountryCodeService extends BaseModelService
{

    public static function getModel()
    {
        return new CountryCodeModel;
    }

    public static function addCountryCode($param){
        $item =  Helper::arrayCamelKeyToUnderscore($param);
        return self::add($item);
    }

    public static function updateCountryCode($param){
        $id = $param['isocode'];
        unset($param['isocode']);
        $origin = self::getBase($id);  
        if(empty($origin)){            
            throw new ApiException("origin data is not exist",ErrnoPlus::COMMON_ERROR);
        }
        $item = Helper::arrayCamelKeyToUnderscore($param);
        $update = [];
        foreach($item as $key => $val){
            if($val != $origin[$key]){
                $update[$key] = $val;
            }
        }
        if(count($update) > 0){
            self::update($id,$update);
        }
    }

    public static function delCountryCode($id){
        return self::del($id);
    }

    public static function buildCondition($filter)
    {
        $res = [];
        if(isset($filter['isocode']) && !empty($filter['isocode'])){
            $res['isocode'] = $filter['isocode'];
        }

        if(isset($filter['phoneCode']) && !empty($filter['phoneCode'])){
            $res['phone_code'] = $filter['phoneCode'];
        }

        if(isset($filter['location']) && !empty($filter['location'])){
            $res['location'] = ['like',"%".$filter['location']."%"];
        }

        if(isset($filter['locationName']) && !empty($filter['locationName'])){
            $res['location_name'] = ['like',"%".$filter['locationName']."%"];
        }
        return $res;
    }
}
